package everyday;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/6/8 16:13
 * 82. 删除排序链表中的重复元素 II
 * https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/
 */
public class Solution82 {

    // 一次遍历
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode headNode = new ListNode(-1);  // 辅助头节点, 最终返回 head.next
        headNode.next = head;
        ListNode cur = headNode;
        while (cur.next != null && cur.next.next != null) {
            if (cur.next.val == cur.next.next.val) {
                int curVal = cur.next.val;
                while (cur.next != null && cur.next.val == curVal) {
                    cur.next = cur.next.next;
                }
            } else {
                cur = cur.next;
            }
        }
        return headNode.next;
    }

    // 递归思路
    public ListNode deleteDuplicates2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        if (head.val != head.next.val) {
            head.next = deleteDuplicates2(head.next);
        } else {
            ListNode move = head;
            while (move != null && move.val == head.val) {
                move = move.next;
            }
            return deleteDuplicates2(move);
        }
        return head;
    }


        private class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
